﻿using System;
using System.Collections.Generic;

namespace Telex;

sealed partial class RpcChannel
{
    private List<ResponseUnit> timeoutResponseUnits = new();
    private List<VerifyUnit> timeoutVerifyUnits = new();
    
    private void OnTimerEvent(long timestamp)
    {
        foreach (var unit in this.responseUnits)
        {
            if (timestamp >= unit.Value.timestamp)
            {
                this.timeoutResponseUnits.Add(unit.Value);
            }
        }
        foreach (var unit in this.timeoutResponseUnits)
        {
            this.responseUnits.TryRemove(unit.uid, out _);
            unit.func.Invoke(Array.Empty<byte>(), TelexOpcode.TIMEOUT);
        }
        
        
        foreach (var unit in this.waitVerifyUnits)
        {
            if (timestamp >= unit.Value.timestamp)
            {
                this.timeoutVerifyUnits.Add(unit.Value);
            }
        }
        foreach (var unit in this.timeoutVerifyUnits)
        {
            waitVerifyUnits.TryRemove(unit.pak.hash, out _);
            unit.pak.Dispose();
        }

        this.timeoutResponseUnits.Clear();
        this.timeoutVerifyUnits.Clear();
    }
}